/*
 * Copyright 2008 - 2009 Lars Heuer (heuer[at]semagia.com). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.semagia.atomico.server.impl.jaxrs;

import java.io.InputStream;
import java.util.Date;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;

import com.semagia.atomico.MediaType;
import com.semagia.atomico.dm.IWritableRepresentation;
import com.semagia.atomico.server.UnsupportedMediaTypeException;
import com.semagia.atomico.server.dm.ICollectionInfo;
import com.semagia.atomico.server.dm.ISnapshotInfo;
import com.semagia.atomico.server.storage.IModifiableStorage;
import com.semagia.atomico.server.storage.StorageException;
import com.semagia.atomico.server.utils.LinkUtils;

/**
 * Resource representing a list of available snapshots for a particular 
 * collection.
 * 
 * @author Lars Heuer (heuer[at]semagia.com) <a href="http://www.semagia.com/">Semagia</a>
 */
public final class SnapshotsFeedResource extends AbstractCollectionAwareFeedResource {

    private final long _lastModification;

    SnapshotsFeedResource(final Request req, final UriInfo uriInfo, 
            final ICollectionInfo collInfo) throws StorageException {
        super(req, uriInfo, collInfo);
        _lastModification = getStorage().lastSnapshotModification(_collInfo.getCollectionId());
    }

    /* (non-Javadoc)
     * @see com.semagia.atomico.server.impl.jaxrs.AbstractBaseResource#lastModification()
     */
    @Override
    protected long lastModification() {
        return _lastModification;
    }

    @GET
    @Produces("*/*")
    public Response getSnapshots(@Context HttpHeaders headers) throws StorageException, UnsupportedMediaTypeException {
        final Response.ResponseBuilder builder = makeResponseBuilder();
        final IWritableRepresentation writable = 
            _feedFactory.createSnapshotsFeed(getBaseURI(),
                    getStorage(), getConfiguration(), _lastModification,
                    _collInfo, MediaTypeUtils.toAtomicoMediaType(headers.getAcceptableMediaTypes()));
        return ResponseUtils.buildStreamingEntity(builder, writable);
    }

    @Path("/{snapshot}")
    public SnapshotResource getSnapshot(@PathParam("snapshot") String snapshot) throws StorageException {
        return new SnapshotResource(_request, _collInfo, snapshot);
    }

    /**
     * Adds a snapshot.
     *
     * @param in
     * @param headers
     * @return
     * @throws StorageException
     * @throws UnsupportedMediaTypeException 
     */
    @POST
    public Response addSnapshot(final InputStream in, @Context HttpHeaders headers) throws StorageException, UnsupportedMediaTypeException {
        final IModifiableStorage storage = super.getModifiableStorage();
        final MediaType mediaType = MediaTypeUtils.toAtomicoMediaType(headers.getMediaType());
        // Reject request iff the media type is null.
        if (mediaType == null) {
            // 415 == Unsupported Media Type
            return Response.status(415).build();
        }
        final ISnapshotInfo info = storage.addSnapshot(_collInfo.getCollectionId(), null);
        if (info == null) {
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }
        return Response.created(LinkUtils.linkTo(getBaseURI(), _collInfo, info))
                        .lastModified(new Date(info.getUpdated()))
                        .build();
    }

}
